<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>问候语管理</span>
      </div>
    </template>
    <el-form ref="queryFormRef" :module="queryParams" label-width="100px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="问候语名称">
            <el-input
              v-model="queryParams.greetType"
              placeholder="请输入问候语名称"
              clearable
              @keyup.enter="getList"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="问候语内容">
            <el-input
              v-model="queryParams.greetContent"
              placeholder="请输入问候语内容"
              clearable
              @keyup.enter="getList"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row>
      <el-row :span="6">
        <el-button @click="openForm('create')" type="primary">新建</el-button>
        <el-button @click="goToCommuntion" type="primary">去对话侧</el-button>
      </el-row>
      <el-col :span="6" :offset="21" justify="end">
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-col>
    </el-row>

    <el-row style="margin-top: 20px">
      <el-col>
        <el-table
          border
          v-loading="loading"
          :data="list"
          stripe
          ref="tableRef"
          style="width: 100%"
          max-height="430px"
          :row-style="{
            height: '70px',
          }"
          :row-key="(row:any) => row.id"
          :header-cell-style="{
            background: '#f5f5f5',
            color: '#303133',
            height: '70px',
          }"
          show-overflow-tooltip
        >
          <el-table-column
            prop="id"
            label="问候语id"
            width="180"
            fixed="left"
          />
          <el-table-column
            prop="greetType"
            label="问候语名称"
            width="180"
            fixed="left"
          />
          <el-table-column
            min-width="160"
            prop="greetContent"
            label="问候语内容"
            width="180"
          />
          <el-table-column min-width="180" prop="createTime" label="创建时间">
            <template #default="{ row }">
              {{
                row.createTime &&
                dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
              }}
            </template>
          </el-table-column>
          <el-table-column min-width="180" prop="updateTime" label="修改时间">
            <template #default="{ row }">
              {{
                row.updateTime &&
                dayjs(row.updateTime).format('YYYY-MM-DD HH:mm:ss')
              }}
            </template>
          </el-table-column>
          <el-table-column min-width="180" prop="createId" label="创建人id" />
          <el-table-column min-width="180" prop="updateId" label="修改人id" />
          <el-table-column min-width="180" label="操作" fixed="right">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="openForm('edit', scope.row)"
              >
                编辑
              </el-button>
              <el-button
                link
                type="primary"
                size="small"
                @click="detail(scope.row)"
              >
                查看
              </el-button>
              <el-button
                link
                type="danger"
                size="small"
                @click="handleDelete(scope.row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <div style="display: flex; justify-content: end; margin-top: 15px">
      <el-pagination
        background
        v-model:current-page="queryParams.currentPage"
        v-model:page-size="queryParams.pageSize"
        layout="prev, pager, next"
        :page-sizes="[10, 20, 30, 40]"
        :total="total"
        @change="() => getList()"
      />
    </div>
  </el-card>
  <Detail ref="detailDialog" />
  <FromDialog ref="fromDialogRef" @changeData="changeData" :getList="getList" />
</template>

<script setup lang="ts">
import Detail from './components/dialog.vue'
import { debounce } from '@/utils/debounce'
import { nextTick, onMounted, ref } from 'vue'
import robotData from './welcomeData.json'
import { ElMessage, ElMessageBox } from 'element-plus'
import FromDialog from './components/form.vue'
import { useRouter } from 'vue-router'
import * as WelcomeApi from '@/api/welcome/index'
import dayjs from 'dayjs'

const list = ref()
const queryParams = ref({
  currentPage: 0,
  pageSize: 10,
  greetType: '', // 问候语类型
  greetContent: '', // 问候语内容
})

let router = useRouter()
const goToCommuntion = () => {
  router.push({ name: 'communication' })
}

const changeData = (val: object) => {
  const filterListValue = list.value.filter((item: any) => item.id != val.id)
  list.value = [val, ...filterListValue]
  list.value.sort((a: any, b: any) => a.id - b.id)
}

const loading = ref(false)
const total = ref(0)
const detailDialog = ref()
const fromDialogRef = ref()

const openForm = (type: string, row?: any) => {
  if (type === 'create') {
    fromDialogRef.value.open('create')
  } else {
    fromDialogRef.value.open('edit', row)
  }
}

const detail = (row: any) => {
  detailDialog.value.open(row)
}

const resetQuery = debounce(() => {
  resetForm()
  handleQuery()
}, 500)

const resetForm = () => {
  queryParams.value.greetType = ''
  queryParams.value.greetContent = ''
}

const handleQuery = () => {
  queryParams.value.currentPage = 1
  getList()
}

// 删除按钮的二次确认框
const handleDelete = (id: number | string) => {
  ElMessageBox.confirm('删除后无法恢复，请仔细考虑?', '确认删除本条数据', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    type: 'warning',
  })
    .then(async () => {
      // list.value = await list.value.filter((item: any) => item.id !== id)
      const res = (await WelcomeApi.welcomeDelete(id)) as any
      if (res.flag) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        getList()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除失败',
      })
    })
}

const getList = async () => {
  loading.value = true
  // setTimeout(() => {
  //   loading.value = false
  // }, 300)
  try {
    const res = (await WelcomeApi.welcomeTable(queryParams.value)) as any
    total.value = res.total
    list.value = res.data.list
  } catch {
    list.value = []
  } finally {
    loading.value = false
  }

  // list.value = robotData.map((item) => {
  //   return {
  //     id: item.id,
  //     greetType: item.greetType,
  //     greetContent: item.greetContent,
  //     createTime: item.createTime,
  //     updateTime: item.updateTime,
  //     createId: item.createId,
  //     updateId: item.updateId,
  //   }
  // })
  // total.value = list.value.length
}

onMounted(() => {
  handleQuery()
  // setTimeout(() => {
  //   loading.value = false
  // }, 300)
})
</script>
